<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;

        $cateModel = model('app\common\model\Category');

        $tree = Tree::instance();
        $tree->init(collection($cateModel->order('weigh desc,id desc')->select())->toArray(), 'pid', ' ');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $this->view->assign("parentList", $categorydata);

    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $where1 = [];
        $cid = input('cid/d', 0);
        if($cid > 0){
            $where1['category_id'] = $cid;
        }

        $keywords = input('keywords/s', '');
        if($keywords){
            $where1['title|remark'] = ['like','%'.$keywords.'%'];
        }

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignconfig('cid',$cid);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where1)
            ->with(['category'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $cid = input('cid/d', 0);
        if (false === $this->request->isPost()) {
            $this->assign('category_id',$cid);
            return $this->view->fetch('project/edit');
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

//    public function detail($ids = null)
//    {
//        $info = $this->model->get($ids);
//        $title = explode(',',$info['title']);
//        $this->assign('thead', $title);
//        $title_length = count($title);
//
//        $sum = [];
//        foreach ($title as $k => $v) {
//            $sum[$k] = 0;
//        }
//
//        $content = explode("\r", $info['content']);
//        $this->assign('content',$content);
//
//        $lines = [];
//        foreach ($content as $k => $v) {
//            $index = array_search($v, $title);
//            $sum[$this->search_arr_key($index-1,$title_length)] += 1;
//            $sum[$this->search_arr_key($index-2,$title_length)] += 1;
//            $sum[$this->search_arr_key($index+1,$title_length)] += 1;
//            $sum[$this->search_arr_key($index+2,$title_length)] += 1;
//
//            $lines[] = $sum;
//        }
//        $this->assign('lines', $lines);
//
//
//        return $this->view->fetch();
//    }

    public function attach()
    {
        ini_set('memory_limit', '1024M');

        $params = $this->request->post();
        $content = json_decode($params['content'], true);



        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $spreadsheet->getDefaultStyle()
            ->getFont()
            ->setSize(13); // 默认11磅

        $sheet->setCellValue('A1','行首');
        $title = explode(',',$params['title']);
        foreach ($title as $k => $v) {
            $sheet->setCellValueByColumnAndRow($k+2, 1, $v);
        }

        $sheet->setCellValue('A2','总计');
        $sum = explode(',',$params['sum']);
        foreach ($sum as $k => $v) {
            $sheet->setCellValueByColumnAndRow($k+2, 2, $v);
        }

        $sheet->mergeCells('C13:E13');
        $sheet->setCellValue('C13',$params['remark']);

        $sheet->mergeCells('C14:E14');
        $sheet->setCellValue('C14',$params['explain']);


//        $sheet->getColumnDimension('A')->setWidth(20);


        foreach ($content as $k => $v) {
            $sheet->setCellValue('A'.($k+4),(String)$v['num']);
            $sheet->setCellValue('B'.($k+4),$v['str']);
        }

        // 获取实际使用的最大行和列
        $lastRow = $sheet->getHighestRow(); // 获取有数据的最后一行
        $lastColumn = $sheet->getHighestColumn(); // 获取有数据的最后一列

// 设置整个数据区域居中
        $sheet->getStyle('A1:' . $lastColumn . $lastRow)
            ->getAlignment()
            ->setHorizontal(Alignment::HORIZONTAL_CENTER)
            ->setVertical(Alignment::VERTICAL_CENTER);

        // 创建 Xlsx 写入器（使用Xlsx格式而不是Xls，因为现代浏览器支持更好）
        $writer = new Xls($spreadsheet);

        // 直接输出到浏览器
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: inline; filename="' . date("Y-m-d") . '.xls"');

        // 清除输出缓冲
        ob_clean();
        flush();

        // 直接输出到浏览器
        $writer->save('php://output');
        exit;


//        $writer = new Xls($spreadsheet);
//        $filename=date("Y-m-d");
//        $writer->save($filename);
//        header('Content-Type: application/vnd.ms-excel');
//        header('Content-Disposition: attachment;filename='.$filename);
//        header('Cache-Control: max-age=0');
//        ob_clean();
//        flush();
//        readfile($filename);//输出文件;
    }

    //匹配数组的时候支持负数
//    private function search_arr_key($key,$length)
//    {
//        if($key>=$length){
//            return $key-$length;
//        }elseif ($key<0){
//            return $key+$length;
//        }else{
//            return $key;
//        }
//    }


}
